<?php

namespace Backend\Controller;
use Think\Controller;

class ElasticController extends BaseController
{




    public function _initialize() {
        Vendor('Elasticsearch.autoload');
        $params['hosts'] = array(
            '106.75.31.101:9200'
        );
        $this->client = new \Elasticsearch\Client($params);
    }

    /**
     * 增加
     */
    public function add_document(){
        $params = array();
        $params['body'] = array( 'testField' => 'dfdsfdsf', 'ok' => '1' );
        $params['index'] = 'dsp';
        $params['type'] = 'xm_click';
        $params['id'] = '222'; $ret = $this->client->index($params);
        dump($ret);
    }

    /**
     * 创建索引
     *使用自己的ID

     *只要再添加一个id字段即可。例：
     * $indexParams['id'] = '123';
     */

    public function create_index() {
        $indexParams['index'] = 'dsp';
        $indexParams['type'] = 'xm_click';
        $indexParams['body']['settings']['number_of_shards'] = 2;
        $indexParams['body']['settings']['number_of_replicas'] = 0;
        $indexParams['id'] = '5698';
        $aa =$this->client->create($indexParams);

        dump($aa);

    }

    /**
     * 根据id、index、type来查询（一条数据，精确查询）
     */
    public function get_document(){
        $getParams = array();
        $getParams['index'] = 'dsp';
        $getParams['type'] = 'nmg';
        $getParams['id'] = '593f8145d85b022321649453';
        $retDoc = $this->client->get($getParams);
        dump($retDoc);
    }

    /**
     * 检查文档是否存在
     *
     */
    public function exists(){
        $getParams = array(
            'index' => 'my_index',
            'type' => 'my_index',
            'id' => 'w1231313'
        );

        $exists = $this->client->exists($getParams);
        dump($exists);
    }

    /**
     * 删除索引
     */
    public function delete_index(){
        $deleteParams['index'] = 'dsp';
        $ret = $this->client->indices()->delete($deleteParams);
        dump($ret);
    }

    /**
     * 模糊查询
     */
    public function search_() {
        $searchParams = array();
        $searchParams['body'] = array( 'query' => array( 'match' => array( 'testField' => 'dfdsfdsf' ) ) );
        $retDoc = $this->client->search($searchParams);
        dump($retDoc);
    }

    /**
     * 修改
     */
    public function update_document(){
        $updateParams = array();
        $updateParams['index'] = 'my_index';
        $updateParams['type'] = 'my_index';
        $updateParams['id'] = 'w1231313';
        $updateParams['body']['doc']['testField'] = 'xxxx';
        $response = $this->client->update($updateParams);
        dump($response);
    }

    /**
     * 删除
     *
     */
    public function delete_document(){
        $deleteParams = array();
        $deleteParams['index'] = 'my_index';
        $deleteParams['type'] = 'my_index';
        $deleteParams['id'] = 'w1231313';
        $retDelete = $this->client->delete($deleteParams);
        dump($retDelete);
    }

    /**
     * 空查询
     */
    public function search(){
        $retDoc = $this->client->search();
        dump($retDoc);
    }

    /**
     * term : 相当于模糊查询
     * match : 相当于精确查询
     * 查询与过滤
     */

    public function test111(){
        $params['index'] = 'my_index';
        $params['type'] = 'my_index';
        $filter = array();
        $filter['term']['my_field'] = 'abc';
        $query = array();
        $query['match']['my_other_field'] = 'xyz';
        $params['body']['query']['filtered'] = array( "filter" => $filter, "query" => $query );
        $results = $this->client->search($params);
        dump($results);
    }

    /**
     * 分页
     * from : 跳过开始的结果数，默认0
     * size: 结果数，默认为10
     */

    public function search_size(){
        $searchParams['index'] = 'my_index';
        $searchParams['type'] = 'my_index';
        $searchParams['from'] = 0;
        $searchParams['size'] = 100;
        $retDoc = $this->client->search($searchParams);
        dump($retDoc);
    }

    /**
     * must : 多个查询条件的完全匹配,相当于 and。
     * must_not : 多个查询条件的相反匹配，相当于 not。
     * should : 至少有一个查询条件匹配, 相当于 or。
     * 布尔查询
     */

    public function boolquery(){
        $params['index'] = 'my_index';
        $params['type'] = 'my_index';
        $params['body']['query']['bool']['must'] = array( array('match' => array('testField' => 'abc')), array('match' => array('anotherTestField' => 'xyz')), );
        $params['body']['query']['bool']['must_not'] = array( array('term' => array('testField' => 'abc')) );
        $results = $this->client->search($params);
        dump($results);
    }
/************************************************************统计 ***************************************************************/
    /**
     * 整体报告
     */
    public  function  total_Statistics() {

    //定义查询条件
        $data = $_GET;
        if(empty($data['begin']) && empty($data['end'])){
            $data['end'] =date("Y-m-d",strtotime("-1 day"));
            $data['begin']=date("Y-m-d",strtotime("-1 week"));

        }
        $json =[
            "size" => 0,
            "query"=>[
                "bool"=>[
                    "must"=>[ "match" =>["user_id" => $_SESSION['id']]],
                    "filter"=>[
                        "range"=>[
                            "cdate"=>[
                                "gte"=> $data['begin'],
                                "lte"=> $data['end']
                            ]
                        ]
                    ]
                ]
            ],

            "aggs" =>[
                "group_by_cdate"=>[
                    "date_histogram"=>[
                        "field"=> "cdate",
                        "interval"=> "day",
                        "min_doc_count"=>0,
                        "format"=> "yyyy-MM-dd",
                        "extended_bounds"=>[
                            "min"=> $data['begin'],
                            "max"=>$data['end']
                        ]
                    ]

                ]
            ],
        ];
        //调用方法 查询结果
        $click = $this->_search('dsp','xm_click',$json);
        $view = $this->_search('dsp','xm_view',$json);

        $click_data = $click['aggregations']['group_by_cdate']['buckets'];
        $view_data = $view['aggregations']['group_by_cdate']['buckets'];


        //遍历处理数据
        foreach ($click_data as $k =>$v ){
            $results['total_click'][] = $click_data[$k]['doc_count'];
            $results['time'][] = $click_data[$k]['key_as_string'];
            foreach ( $view_data as  $k1 =>$v1){

                if($v['key_as_string'] == $v1['key_as_string']){
                    $results['total_click_rate'][] = empty($v1['doc_count']) ? 0 : round($v['doc_count'] / $v1['doc_count'] * 100, 2);
                    $results['total_view'][] = $view_data[$k1]['doc_count'];
                }
            }

        }

        foreach ( $results as $k2 => $v2) {
            foreach ($v2 as $key => $val) {
                $res[$key][$k2][] = $val;
            }
        }


        $results['total_list'] = $res;

        //总展现量点击量
        $total_click_sum =$this->_search('dsp','xm_click',$json);
        $total_view_sum  =$result =$this->_search('dsp','xm_view',$json);
        $total_click_rate_sum = empty($total_view_sum['hits']['total']) ? 0 : round($total_click_sum['hits']['total']/$total_view_sum['hits']['total']*100,2);


        $results['total_click_sum'] = $total_click_sum['hits']['total'];
        $results['total_view_sum'] = $total_view_sum['hits']['total'];
        $results['total_click_rate_sum'] = $total_click_rate_sum;


        $this->ajaxReturn(['status' => '1', 'msg' => 'ok', 'data' => $results]);
    }

    /*
     * 资源报告————代码位报告
     */
    public  function  code_Statistics() {

        $data = $_GET;

        //定义查询条件
        if(empty($data['codeid'])){

          $results =$this ->serach_json($data);
            //时间范围内每个代码位的点击和展现
            if(empty($data['begin']) && empty($data['end'])){
                $data['end'] =date("Y-m-d",strtotime("-1 day"));
                $data['begin']=date("Y-m-d",strtotime("-1 week"));

            }

            $json_1 =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[ "match" =>["user_id" => $_SESSION['id']]],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" =>[
                    "group"=>[
                        "terms"=>[
                            "field"=> "codeid.keyword"

                        ]

                    ]
                ],
            ];




            $code_click_re = $this->_search('dsp','xm_click',$json_1);
            $code_view_re = $this->_search('dsp','xm_view',$json_1);
            $code_click_res =$code_click_re['aggregations']['group']['buckets'];
            $code_view_res =$code_view_re['aggregations']['group']['buckets'];


            if(empty($code_click_res)) {
                foreach ($code_view_res as $k =>$v) {
                    $code_name = D('Code') ->field('code_name') ->where(array('id' =>$v['key']))->find();
                    $res_code[$k]['code_name'] =$code_name['code_name'];
                    $res_code[$k]['codeid'] = $v['key'];
                    $res_code[$k]['code_view'] = $v['doc_count'];
                    $res_code[$k]['code_click'] = 0;
                    $res_code[$k]['code_click_rate'] = 0;
                }
            }
            if(empty($code_view_res)) {
                    $res_code[0]['code_name'] ='没有数据';
                    $res_code[0]['codeid'] ='没有数据';
                    $res_code[0]['code_view'] = '没有数据';
                    $res_code[0]['code_click'] = '没有数据';
                    $res_code[0]['code_click_rate'] ='没有数据';
            }

            if(!empty($code_click_res) && !empty($code_view_res)) {
                $code_value =$this ->get_total_datas ($code_view_res,$code_click_res);
                foreach ($code_value as $kk =>$vv) {
                    $code_name = D('Code') ->field('code_name') ->where(array('id' =>$kk))->find();
                    $res_code[$kk]['code_name'] =$code_name['code_name'];
                    $res_code[$kk]['codeid'] = $kk;
                    $res_code[$kk]['code_view'] = $vv['view'];
                    $res_code[$kk]['code_click'] = $vv['click'];
                    $res_code[$kk]['code_click_rate'] = empty($vv['view']) ? 0 : round($vv['click'] / $vv['view']*100,2);

                }

            }


          $results['code_list'] = $res_code;

        } else{
            if(empty($data['begin']) && empty($data['end'])){
                $data['end'] =date("Y-m-d",strtotime("-1 day"));
                $data['begin']=date("Y-m-d",strtotime("-1 week"));

            }

            $json =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[
                            [ "match" =>["user_id" => $_SESSION['id']]],
                            [ "match" =>["codeid" => $data['codeid']]]
                        ],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" =>[
                    "group_by_cdate"=>[
                        "date_histogram"=>[
                            "field"=> "cdate",
                            "interval"=> "day",
                            "min_doc_count"=>0,
                            "format"=> "yyyy-MM-dd",
                            "extended_bounds"=>[
                                "min"=> $data['begin'],
                                "max"=>$data['end']
                            ]
                        ]

                    ]
                ],
            ];

            $code_click = $this->_search('dsp','xm_click',$json);
            $code_view = $this->_search('dsp','xm_view',$json);
            //var_dump($code_view)
            $code_click_data = $code_click['aggregations']['group_by_cdate']['buckets'];
            $code_view_data = $code_view['aggregations']['group_by_cdate']['buckets'];

            //遍历处理数据
            foreach ($code_click_data as $k =>$v ){
                $results['click'][] = $code_click_data[$k]['doc_count'];
                $results['time'][] = $code_click_data[$k]['key_as_string'];
                foreach ( $code_view_data as  $k1 =>$v1){

                    if($v['key_as_string'] == $v1['key_as_string']){
                        $results['click_rate'][] = empty($v1['doc_count']) ? 0 : round($v['doc_count'] / $v1['doc_count'] * 100, 2);
                        $results['view'][] = $code_view_data[$k1]['doc_count'];
                    }
                }

            }
            //时间范围内每个代码位的点击和展现

            $json_1 =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[
                            [ "match" =>["user_id" => $_SESSION['id']]],
                            [ "match" =>["codeid" => $data['codeid']]]
                        ],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" =>[
                    "group"=>[
                        "terms"=>[
                            "field"=> "codeid.keyword"
                        ]

                    ]
                ],
            ];




            $code_click_re = $this->_search('dsp','xm_click',$json_1);
            $code_view_re = $this->_search('dsp','xm_view',$json_1);

            $code_click_res =$code_click_re['aggregations']['group']['buckets'];
            $code_view_res =$code_view_re['aggregations']['group']['buckets'];

           // var_dump($code_view_res);exit;
            $code_name = D('Code')->field('code_name')->where(array('codeid' =>$data['codeid']))->find();


            if($code_view_res) {
                $res_code[0]['codeid'] = $code_view_res[0]['key'];
                $res_code[0]['code_view'] = $code_view_res[0]['doc_count'];
                $res_code[0]['code_click'] = empty($code_click_res[0]['doc_count']) ? 0 : $code_click_res[0]['doc_count'];
                $res_code[0]['code_name'] =  $code_name['code_name'];
                $res_code[0]['code_click_rate'] =   empty($code_view_res[0]['doc_count']) ? 0 : round($code_click_res[0]['doc_count'] / $code_view_res[0]['doc_count'] * 100, 2);
            }else {
                $res_code[0]['codeid'] = '没有数据';
                $res_code[0]['code_view'] = '没有数据';
                $res_code[0]['code_click'] = '没有数据';
                $res_code[0]['code_name'] =  '没有数据';
                $res_code[0]['code_click_rate'] ='没有数据';
            }


            $results['code_list'] = $res_code;

            //总展现量点击量
            $code_click_sum =$this->_search('dsp','xm_click',$json);
            $code_view_sum  =$result =$this->_search('dsp','xm_view',$json);
            $code_click_rate_sum = empty($code_view_sum['hits']['total']) ? 0 : round($code_click_sum['hits']['total']/$code_view_sum['hits']['total']*100,2);


            $results['click_sum'] = $code_click_sum['hits']['total'];
            $results['view_sum'] = $code_view_sum['hits']['total'];
            $results['click_rate_sum'] = $code_click_rate_sum;
        }





        $this->ajaxReturn(['status' => '1', 'msg' => 'ok', 'data' => $results]);
    }


    /**
     * 投放报告————广告报告
     *
     */

    public  function  delivery_Statistics() {
        $data =$_GET;


        if(empty($data['delivery_id'])) {
            if(empty($data['begin']) && empty($data['end'])){
                $data['end'] =date("Y-m-d",strtotime("-1 day"));
                $data['begin']=date("Y-m-d",strtotime("-1 week"));

            }

          $results =$this ->serach_json($data);

            //时间范围内每个代码位的点击和展现

            $json_1 =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[ "match" =>["user_id" => $_SESSION['id']]],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" =>[
                    "group"=>[
                        "terms"=>[
                            "field"=> "delivery_id.keyword"
                        ]

                    ]
                ],
            ];

            $delivery_click_re = $this->_search('dsp','xm_click',$json_1);

            $delivery_view_re = $this->_search('dsp','xm_view',$json_1);
            $delivery_click_res =$delivery_click_re['aggregations']['group']['buckets'];
            $delivery_view_res =$delivery_view_re['aggregations']['group']['buckets'];
            if(empty($delivery_click_res) && !empty($delivery_view_res)) {
                foreach ($delivery_view_res as $k =>$v) {
                    $delivery_name = D('Ad_delivery') ->field('ad_name as delivery_name') ->where(array('id' =>$v['key']))->find();
                    $use_amount = D('Ad_delivery') ->field('use_amount') ->where(array('id' =>$v['key']))->find();
                    $res_delivery[$k]['delivery_name'] =$delivery_name['delivery_name'];
                    $res_delivery[$k]['use_amount']=  $use_amount['use_amount'];
                    $res_delivery[$k]['delivery_id'] = $v['key'];
                    $res_delivery[$k]['delivery_view'] = $v['doc_count'];
                    $res_delivery[$k]['delivery_click'] = 0 ;
                    $res_delivery[$k]['delivery_click_rate'] = 0 ;

                }
            }

            if(empty($delivery_view_res)) {
                $res_delivery[0]['delivery_name'] ='没有数据';
                $res_delivery[0]['use_amount']=  '没有数据';
                $res_delivery[0]['delivery_id'] = '没有数据';
                $res_delivery[0]['delivery_view'] ='没有数据';
                $res_delivery[0]['delivery_click'] ='没有数据';
                $res_delivery[0]['delivery_click_rate'] = '没有数据';
            }

            if(!empty($delivery_view_res) && !empty($delivery_click_res)) {
                $delivery_value =$this ->get_total_datas ($delivery_view_res,$delivery_click_res);
                foreach ($delivery_value as $kk =>$vv) {
                    $delivery_name = D('Ad_delivery') ->field('ad_name as delivery_name') ->where(array('id' =>$kk))->find();
                    $use_amount = D('Ad_delivery') ->field('use_amount') ->where(array('id' =>$kk))->find();
                    $res_delivery[$kk]['delivery_name'] =$delivery_name['delivery_name'];
                    $res_delivery[$kk]['use_amount']=  $use_amount['use_amount'];
                    $res_delivery[$kk]['delivery_id'] = $kk;
                    $res_delivery[$kk]['delivery_view'] = $vv['view'];
                    $res_delivery[$kk]['delivery_click'] = $vv['click'];
                    $res_delivery[$kk]['delivery_click_rate'] = empty($vv['view']) ? 0 :round($vv['click'] / $vv['view']*100,2);

                }

            }


            $results['delivery_list'] = $res_delivery;

        }else {
            if(empty($data['begin']) && empty($data['end'])){
                $data['end'] =date("Y-m-d",strtotime("-1 day"));
                $data['begin']=date("Y-m-d",strtotime("-1 week"));

            }

            $json =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[
                            [ "match" =>["user_id" => $_SESSION['id']]],
                            [ "match" =>["delivery_id" => $data['delivery_id']]]
                        ],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" =>[
                    "group_by_cdate"=>[
                        "date_histogram"=>[
                            "field"=> "cdate",
                            "interval"=> "day",
                            "min_doc_count"=>0,
                            "format"=> "yyyy-MM-dd",
                            "extended_bounds"=>[
                                "min"=> $data['begin'],
                                "max"=>$data['end']
                            ]
                        ]

                    ]
                ],
            ];

            $code_click = $this->_search('dsp','xm_click',$json);
            $code_view = $this->_search('dsp','xm_view',$json);
            $code_click_data = $code_click['aggregations']['group_by_cdate']['buckets'];
            $code_view_data = $code_view['aggregations']['group_by_cdate']['buckets'];

            //遍历处理数据
            foreach ($code_click_data as $k =>$v ){
                $results['click'][] = $code_click_data[$k]['doc_count'];
                $results['time'][] = $code_click_data[$k]['key_as_string'];
                foreach ( $code_view_data as  $k1 =>$v1){

                    if($v['key_as_string'] == $v1['key_as_string']){
                        $results['click_rate'][] = empty($v1['doc_count']) ? 0 : round($v['doc_count'] / $v1['doc_count'] * 100, 2);
                        $results['view'][] = $code_view_data[$k1]['doc_count'];
                    }
                }

            }
            //时间范围内每个投放的点击和展现

            $json_1 =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[
                            [ "match" =>["user_id" => $_SESSION['id']]],
                            [ "match" =>["delivery_id" => $data['delivery_id']]]
                        ],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" =>[
                    "group"=>[
                        "terms"=>[
                            "field"=> "delivery_id.keyword"
                        ]

                    ]
                ],
            ];




            $code_click_re = $this->_search('dsp','xm_click',$json_1);
            $code_view_re = $this->_search('dsp','xm_view',$json_1);
            $code_click_res =$code_click_re['aggregations']['group']['buckets'];
            $code_view_res =$code_view_re['aggregations']['group']['buckets'];


            $code_name = D('Ad_delivery')->field('ad_name as delivery_name')->where(array('id' =>$data['delivery_id']))->find();
            $use_amount = D('Ad_delivery')->field('use_amount')->where(array('id' =>$data['delivery_id']))->find();

            if($code_view_res) {
                $res_code[0]['delivery_id'] = $code_view_res[0]['key'];
                $res_code[0]['delivery_view'] = $code_view_res[0]['doc_count'];
                $res_code[0]['delivery_click'] = empty($code_click_res[0]['doc_count'])? 0: $code_click_res[0]['doc_count'];
                $res_code[0]['delivery_name'] =  $code_name['delivery_name'];
                $res_code[0]['use_amount'] =  $use_amount['use_amount'];
                $res_code[0]['delivery_click_rate'] =   empty($code_view_res[0]['doc_count']) ? 0 : round($code_click_res[0]['doc_count'] / $code_view_res[0]['doc_count'] * 100, 2);
            }else {
                $res_code[0]['delivery_id'] ='没有数据';
                $res_code[0]['delivery_view'] = '没有数据';
                $res_code[0]['delivery_click'] = '没有数据';
                $res_code[0]['delivery_name'] = '没有数据';
                $res_code[0]['use_amount'] =  '没有数据';
                $res_code[0]['delivery_click_rate'] ='没有数据';
            }


            $results['delivery_list'] = $res_code;

            //总展现量点击量
            $code_click_sum =$this->_search('dsp','xm_click',$json);
            $code_view_sum  =$result =$this->_search('dsp','xm_view',$json);
            $code_click_rate_sum = empty($code_view_sum['hits']['total']) ? 0 : round($code_click_sum['hits']['total']/$code_view_sum['hits']['total']*100,2);


            $results['click_sum'] = $code_click_sum['hits']['total'];
            $results['view_sum'] = $code_view_sum['hits']['total'];
            $results['click_rate_sum'] = $code_click_rate_sum;
        }

        $this->ajaxReturn(['status' => '1', 'msg' => 'ok', 'data' => $results]);
    }

    /**
     * 游戏报告
     */
    public  function  game_Statistics(){
        $data =$_GET;
        if(empty($data['begin']) && empty($data['end'])){
            $data['end'] =date("Y-m-d",strtotime("-1 day"));
            $data['begin']=date("Y-m-d",strtotime("-1 week"));

        }
        if(empty($data['delivery_id'])){
            $json = [
                "size" => 0,
                "query" => [
                    "bool" => [
                        "must"=>[
                            [ "match" =>["user_id" => $_SESSION['id']]],
                            [ "match" =>["is_game" => "1"]]
                        ],
                        "filter" => [
                            "range" => [
                                "cdate" => [
                                    "gte" => $data['begin'],
                                    "lte" => $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" => [
                    "group_by_cdate" => [
                        "date_histogram" => [
                            "field" => "cdate",
                            "interval" => "day",
                            "min_doc_count" => 0,
                            "format" => "yyyy-MM-dd",
                            "extended_bounds" => [
                                "min" => $data['begin'],
                                "max" => $data['end']
                            ]
                        ]

                    ]
                ],
            ];
            $code_click = $this->_search('dsp','xm_click',$json);
            $code_view = $this->_search('dsp','xm_view',$json);
            $code_click_data = $code_click['aggregations']['group_by_cdate']['buckets'];
            $code_view_data = $code_view['aggregations']['group_by_cdate']['buckets'];

            //遍历处理数据
            foreach ($code_click_data as $k =>$v ){
                $results['game_click'][] = $code_click_data[$k]['doc_count'];
                $results['time'][] = $code_click_data[$k]['key_as_string'];
                foreach ( $code_view_data as  $k1 =>$v1){

                    if($v['key_as_string'] == $v1['key_as_string']){
                        $results['game_click_rate'][] = empty($v1['doc_count']) ? 0 : round($v['doc_count'] / $v1['doc_count'] * 100, 2);
                        $results['game_view'][] = $code_view_data[$k1]['doc_count'];
                    }
                }

            }

            //时间范围内每个的点击和展现

            $json_1 =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[
                            [ "match" =>["user_id" => $_SESSION['id']]],
                            [ "match" =>["is_game" => "1"]]
                        ],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" =>[
                    "group"=>[
                        "terms"=>[
                            "field"=> "delivery_id.keyword"
                        ]

                    ]
                ],
            ];

            $delivery_click_re = $this->_search('dsp','xm_click',$json_1);
            $delivery_view_re = $this->_search('dsp','xm_view',$json_1);
            $delivery_click_res =$delivery_click_re['aggregations']['group']['buckets'];
            $delivery_view_res =$delivery_view_re['aggregations']['group']['buckets'];

            $json_2 =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[ "match" =>["has_download" => "1"]],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" =>[
                    "group"=>[
                        "terms"=>[
                            "field"=> "delivery_id.keyword"
                        ]

                    ]
                ],
            ];
            $game_has_download = $this->_search('dsp','xm_game',$json_2);
            $has_download = $game_has_download['aggregations']['group']['buckets'];
            //var_dump($delivery_view_res);exit;


            if(empty($delivery_click_res) && !empty($delivery_view_res)) {
                foreach ($delivery_view_res as $key => $val) {
                    $delivery_name = D('Ad_delivery') ->field('ad_name as delivery_name') ->where(array('id' =>$val['key']))->find();
                    $res_delivery[$key]['delivery_name'] =$delivery_name['delivery_name'];
                    $res_delivery[$key]['delivery_id'] = $val['key'];
                    $res_delivery[$key]['delivery_view'] = $val['doc_count'];
                    $res_delivery[$key]['delivery_click'] = 0;
                    $res_delivery[$key]['delivery_click_rate'] = 0 ;
                    $res_delivery[$key]['has_download'] = 0 ;
                     $res_delivery[$key]['play_time'] = 0;
                }
            }

            if(empty($delivery_view_res)) {
                $res_delivery[0]['play_time']         ='没有数据';
                $res_delivery[0]['has_download']        ='没有数据';
                $res_delivery[0]['delivery_name']     ='没有数据';
                $res_delivery[0]['delivery_id']       = '没有数据';
                $res_delivery[0]['delivery_view']     = '没有数据';
                $res_delivery[0]['delivery_click']    = '没有数据';
                $res_delivery[0]['delivery_click_rate'] = '没有数据';
            }

            if(!empty($delivery_view_res) && !empty($delivery_click_res)) {
                $delivery_value =$this ->get_total_datas ($delivery_view_res,$delivery_click_res);
                foreach ($delivery_value as $kk =>$vv) {
                    foreach ($has_download as $kkk =>$vvv){
                        if($kk == $vvv['key']){
                            $res_delivery[$kk]['has_download'] = $vvv['doc_count'];
                        }
                    }
                    $json_3 =[
                        "size" => 0,
                        "query"=>[
                            "bool"=>[
                                "must"=>[
                                    ["match" =>["delivery_id" => $kk]],
                                    ["match" =>["user_id" => $_SESSION['id']]]
                                ],
                                "filter"=>[
                                    "range"=>[
                                        "cdate"=>[
                                            "gte"=> $data['begin'],
                                            "lte"=> $data['end']
                                        ]
                                    ]
                                ]
                            ]
                        ],

                        "aggs" =>[
                            "sum_play_time"=>[
                                "sum"=>[
                                    "field"=> "play_time"
                                ]

                            ]
                        ],
                    ];
                    $game_play_time = $this->_search('dsp','xm_game',$json_3);

                    $res_delivery[$kk]['play_time'] = round($game_play_time['aggregations']['sum_play_time']['value']/1000,2);
                    $delivery_name = D('Ad_delivery') ->field('ad_name as delivery_name') ->where(array('id' =>$kk))->find();
                    $res_delivery[$kk]['delivery_name'] =$delivery_name['delivery_name'];
                    $res_delivery[$kk]['delivery_id'] = $kk;
                    $res_delivery[$kk]['delivery_view'] = $vv['view'];
                    $res_delivery[$kk]['delivery_click'] = $vv['click'];
                    $res_delivery[$kk]['delivery_click_rate'] = empty($vv['view']) ? 0 :round($vv['click'] / $vv['view']*100,2);

                }
            }

            $results['delivery_list'] = $res_delivery;

            //总展现量点击量
            $code_click_sum =$this->_search('dsp','xm_click',$json);
            $code_view_sum  =$result =$this->_search('dsp','xm_view',$json);
            $code_click_rate_sum = empty($code_view_sum['hits']['total']) ? 0 : round($code_click_sum['hits']['total']/$code_view_sum['hits']['total']*100,2);


            $results['click_sum'] = $code_click_sum['hits']['total'];
            $results['view_sum'] = $code_view_sum['hits']['total'];
            $results['click_rate_sum'] = $code_click_rate_sum;
        }else {


            $json = [
                "size" => 0,
                "query" => [
                    "bool" => [
                        "must"=>[
                                    [ "match" =>["is_game" => "1"]],
                                    ["match" =>["delivery_id" => $data['delivery_id']]],
                                    ["match" =>["user_id" => $_SESSION['id']]]
                                ],
                        "filter" => [
                            "range" => [
                                "cdate" => [
                                    "gte" => $data['begin'],
                                    "lte" => $data['end']
                                ]
                            ]
                        ]
                    ]
                ],

                "aggs" => [
                    "group_by_cdate" => [
                        "date_histogram" => [
                            "field" => "cdate",
                            "interval" => "day",
                            "min_doc_count" => 0,
                            "format" => "yyyy-MM-dd",
                            "extended_bounds" => [
                                "min" => $data['begin'],
                                "max" => $data['end']
                            ]
                        ]

                    ]
                ],
            ];

            $code_click = $this->_search('dsp','xm_click',$json);
            $code_view = $this->_search('dsp','xm_view',$json);
           // var_dump($code_click);exit;
            $code_click_data = $code_click['aggregations']['group_by_cdate']['buckets'];

            $code_view_data = $code_view['aggregations']['group_by_cdate']['buckets'];

            //遍历处理数据
            foreach ($code_click_data as $k =>$v ){
                $results['game_click'][] = $code_click_data[$k]['doc_count'];
                $results['time'][] = $code_click_data[$k]['key_as_string'];
                foreach ( $code_view_data as  $k1 =>$v1){

                    if($v['key_as_string'] == $v1['key_as_string']){
                        $results['game_click_rate'][] = empty($v1['doc_count']) ? 0 : round($v['doc_count'] / $v1['doc_count'] * 100, 2);
                        $results['game_view'][] = $code_view_data[$k1]['doc_count'];
                    }
                }

            }

            //时间范围内每个的点击和展现

            $json_1 =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[
                                [ "match" =>["is_game" => "1"]],
                                ["match" =>["delivery_id" => $data['delivery_id']]],
                                ["match" =>["user_id" => $_SESSION['id']]]
                                ],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ]


            ];

            $delivery_click_re = $this->_search('dsp','xm_click',$json_1);
            $delivery_view_re = $this->_search('dsp','xm_view',$json_1);
            $delivery_click_res =$delivery_click_re['hits']['total'];
            $delivery_view_res =$delivery_view_re['hits']['total'];

            if($delivery_view_res) {
                $res_delivery[0]['delivery_id'] = $data['delivery_id'];
                $res_delivery[0]['delivery_view'] = $delivery_view_res;
                $res_delivery[0]['delivery_click'] =  empty($delivery_click_res) ? 0 : $delivery_click_res ;
                $delivery_name = D('Ad_delivery')->field('ad_name as delivery_name')->where(array('id' =>$data['delivery_id']))->find();
                $res_delivery[0]['delivery_name'] =  $delivery_name['delivery_name'];
                $res_delivery[0]['delivery_click_rate'] = round($delivery_click_re['hits']['total'] / $delivery_view_re['hits']['total'] * 100, 2);



                $json_2 =[
                    "size" => 0,
                    "query"=>[
                        "bool"=>[
                            "must"=>[
                                ["match" =>["has_download" => "1"]],
                                ["match" =>["delivery_id" =>$data['delivery_id']]],
                                ["match" =>["user_id" => $_SESSION['id']]]
                                ],
                            "filter"=>[
                                "range"=>[
                                    "cdate"=>[
                                        "gte"=> $data['begin'],
                                        "lte"=> $data['end']
                                    ]
                                ]
                            ]
                        ]
                    ]



                ];
                $json_3 =[
                    "size" => 0,
                    "query"=>[
                        "bool"=>[
                            "must"=>[
                                ["match" =>["delivery_id" => $data['delivery_id']]],
                                ["match" =>["user_id" => $_SESSION['id']]]
                            ],
                            "filter"=>[
                                "range"=>[
                                    "cdate"=>[
                                        "gte"=> $data['begin'],
                                        "lte"=> $data['end']
                                    ]
                                ]
                            ]
                        ]
                    ],

                    "aggs" =>[
                        "sum_play_time"=>[
                            "sum"=>[
                                "field"=> "play_time"
                            ]

                        ]
                    ],
                ];

           $game_has_download =$this ->_search('dsp','xm_game',$json_2);
            $has_download =$game_has_download['hits']['total'];
            $res_delivery[0]['has_download'] =empty($has_download) ? 0 : $has_download ;
            $game_play_time = $this->_search('dsp','xm_game',$json_3);
            $res_delivery[0]['play_time'] = round($game_play_time['aggregations']['sum_play_time']['value']/1000,2);
            }else{
                $res_delivery[0]['delivery_id'] = '没有数据';
                $res_delivery[0]['delivery_view'] = '没有数据';
                $res_delivery[0]['delivery_click'] =  '没有数据';
                $res_delivery[0]['has_download'] = '没有数据';
                $res_delivery[0]['delivery_name'] = '没有数据';
                $res_delivery[0]['delivery_click_rate'] ='没有数据';
                $res_delivery[0]['play_time'] = '没有数据';
            }

            $results['delivery_list'] = $res_delivery;

            //总展现量点击量
            $code_click_sum =$this->_search('dsp','xm_click',$json);
            $code_view_sum  =$result =$this->_search('dsp','xm_view',$json);
            $code_click_rate_sum = empty($code_view_sum['hits']['total']) ? 0 : round($code_click_sum['hits']['total']/$code_view_sum['hits']['total']*100,2);


            $results['click_sum'] = $code_click_sum['hits']['total'];
            $results['view_sum'] = $code_view_sum['hits']['total'];
            $results['click_rate_sum'] = $code_click_rate_sum;
        }


        $this->ajaxReturn(['status' => '1', 'msg' => 'ok', 'data' => $results]);

    }

    /**
     * 查看每个游戏的详细数据
     */
    public  function  game_list() {
        $data = $_GET;
        if(empty($data['begin']) && empty($data['end'])){
            $data['end'] =date("Y-m-d",strtotime("-1 day"));
            $data['begin']=date("Y-m-d",strtotime("-1 week"));

        }

        if($data['delivery_id']){
            $json =[
                "size" => 0,
                "query"=>[
                    "bool"=>[
                        "must"=>[
                                [ "match" =>["has_download" => "1"]],
                                [ "match" =>["user_id" => $_SESSION['id']]],
                                [ "match" =>["delivery_id" => $data['delivery_id']]]
                                ],
                        "filter"=>[
                            "range"=>[
                                "cdate"=>[
                                    "gte"=> $data['begin'],
                                    "lte"=> $data['end']
                                ]
                            ]
                        ]
                    ]
                ],
                "aggs" =>[
                    "group"=>[
                        "terms"=>[
                            "field"=> "game_id.keyword"
                        ]

                    ]
                ],
            ];
            $game =$this ->_search('dsp','xm_game',$json);
           $game_data = $game['aggregations']['group']['buckets'];

           if ($game_data) {
               foreach ($game_data as $game_k =>$game_val) {

                   $game_name =D('Ad_game')->field('game_name') ->where(array('id' => $game_val['key']))->find();
                   $game_list[$game_k]['game_name'] =   $game_name['game_name'];
                   $game_list[$game_k]['game_id'] = $game_val['key'];
                   $game_list[$game_k]['has_download'] = $game_val['doc_count'];


                   $json_1 =[
                       "size" => 0,
                       "query"=>[
                           "bool"=>[
                               "must"=>[ [ "match" =>["game_id" =>$game_data[$game_k]['key']]],
                                   [ "match" =>["user_id" => $_SESSION['id']]],
                                   [ "match" =>["delivery_id" => $data['delivery_id']]]
                               ],
                               "filter"=>[
                                   "range"=>[
                                       "cdate"=>[
                                           "gte"=> $data['begin'],
                                           "lte"=> $data['end']
                                       ]
                                   ]
                               ]
                           ]
                       ],
                       "aggs" =>[
                           "sum_play_time"=>[
                               "sum"=>[
                                   "field"=> "play_time"
                               ]

                           ]
                       ],
                   ];
                   $game_play_time =$this ->_search('dsp','xm_game',$json_1);
                   $game_list[$game_k]['play_time'] = round($game_play_time['aggregations']['sum_play_time']['value']/1000,2);
               }

           }else {
               $game_list[0]['game_name'] = '没有数据';
               $game_list[0]['game_id'] =  '没有数据';
               $game_list[0]['has_download'] =  '没有数据';
               $game_list[0]['play_time'] =  '没有数据';
           }

        }
        $this->assign('game',$game_list);
        //var_export($game);exit;
        $this->display();


    }

    /***************************************************************************************************************************************************************/
    /**
     * 封装重复的内容
     *
     */
    public function  serach_json ($data){
        if(empty($data['begin']) && empty($data['end'])){
            $data['end'] =date("Y-m-d",strtotime("-1 day"));
            $data['begin']=date("Y-m-d",strtotime("-1 week"));

        }
        $json =[
            "size" => 0,
            "query"=>[
                "bool"=>[
                    "must"=>[ "match" =>["user_id" => $_SESSION['id']]],
                    "filter"=>[
                        "range"=>[
                            "cdate"=>[
                                "gte"=> $data['begin'],
                                "lte"=> $data['end']
                            ]
                        ]
                    ]
                ]
            ],

            "aggs" =>[
                "group_by_cdate"=>[
                    "date_histogram"=>[
                        "field"=> "cdate",
                        "interval"=> "day",
                        "min_doc_count"=>0,
                        "format"=> "yyyy-MM-dd",
                        "extended_bounds"=>[
                            "min"=> $data['begin'],
                            "max"=>$data['end']
                        ]
                    ]

                ]
            ],
        ];
        //调用方法 查询结果
        $click = $this->_search('dsp','xm_click',$json);
        $view = $this->_search('dsp','xm_view',$json);

        $click_data = $click['aggregations']['group_by_cdate']['buckets'];
        $view_data = $view['aggregations']['group_by_cdate']['buckets'];
        //var_dump($view_data);exit;
        //遍历处理数据
        foreach ($click_data as $k =>$v ){
            $results['click'][] = $click_data[$k]['doc_count'];
            $results['time'][] = $click_data[$k]['key_as_string'];
            foreach ( $view_data as  $k1 =>$v1){

                if($v['key_as_string'] == $v1['key_as_string']){
                    $results['click_rate'][] = empty($v1['doc_count']) ? 0 : round($v['doc_count'] / $v1['doc_count'] * 100, 2);
                    $results['view'][] = $view_data[$k1]['doc_count'];
                }
            }

        }

        //总展现量点击量
        $code_click_sum =$this->_search('dsp','xm_click',$json);
        $code_view_sum  =$result =$this->_search('dsp','xm_view',$json);
        $code_click_rate_sum = empty($code_view_sum['hits']['total']) ? 0 : round($code_click_sum['hits']['total']/$code_view_sum['hits']['total']*100,2);


        $results['click_sum'] = $code_click_sum['hits']['total'];
        $results['view_sum'] = $code_view_sum['hits']['total'];
        $results['click_rate_sum'] = $code_click_rate_sum;

        return $results;
    }

    public  function  click_view_sum ($data){
        if(empty($data['begin']) && empty($data['end'])){
            $data['end'] =date("Y-m-d",strtotime("-1 day"));
            $data['begin']=date("Y-m-d",strtotime("-1 week"));

        }
        $json =[
            "size" => 0,
            "query"=>[
                "bool"=>[
                    "must"=>[ "match" =>["user_id" => $_SESSION['id']]],
                    "filter"=>[
                        "range"=>[
                            "cdate"=>[
                                "gte"=> $data['begin'],
                                "lte"=> $data['end']
                            ]
                        ]
                    ]
                ]
            ],

            "aggs" =>[
                "group_by_cdate"=>[
                    "date_histogram"=>[
                        "field"=> "cdate",
                        "interval"=> "day",
                        "min_doc_count"=>0,
                        "format"=> "yyyy-MM-dd",
                        "extended_bounds"=>[
                            "min"=> $data['begin'],
                            "max"=>$data['end']
                        ]
                    ]

                ]
            ],
        ];


        //总展现量点击量
        $total_click_sum =$this->_search('dsp','xm_click',$json);
        $total_view_sum  =$result =$this->_search('dsp','xm_view',$json);
        $total_click_rate_sum = empty($total_view_sum['hits']['total']) ? 0 : round($total_click_sum['hits']['total']/$total_view_sum['hits']['total']*100,2);


        $results['total_click_sum'] = $total_click_sum['hits']['total'];
        $results['total_view_sum'] = $total_view_sum['hits']['total'];
        $results['total_click_rate_sum'] = $total_click_rate_sum;


        return $results;

    }


    /**
     * 定义调用方法
     * @param $index
     * @param $type
     * @param array $param
     * @return mixed
     */

    public function get_total_datas($view, $click) {
        foreach ($view as $vkey => $val) {
            foreach ($click as $ckey => $cval) {
                if ($val['key'] == $cval['key']) {
                    $resKey[$vkey] = $val['key'];
                    $res[$val['key']]['click'] 	= $cval['doc_count'];
                    $res[$val['key']]['view'] 	= $val['doc_count'];
                    break;
                } else {
                    $unKey[$vkey] = $val['key'];
                }
            }
        }

        $views = array_diff($unKey, $resKey);

        foreach ($views as $key => $value) {
            $res[$value]['click'] 	= 0;
            $res[$value]['view'] 	= $view[$key]['doc_count'];
        }

        return $res;
    }

    public  function  _search($index,$type,$param =[]){


        $params['index'] = $index;
        $params['type'] = $type;
        $params['size'] = 100;
        $params['from'] = 0;
        $params['body'] =$param;

        $results = $this->client->search($params);

        return $results;

    }


}

